package com.doit.day01;

import java.sql.*;
import java.util.Iterator;

/**
 * 1.打开mysql中的表
 * 2.读取数据
 * 3.判断是否有下一条数据
 * 4.返回结果
 */
public class MysqlIterator implements Iterator<String> {
    ResultSet resultSet = null;

    public MysqlIterator() throws SQLException {
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test01", "root", "123456");
        PreparedStatement pps = conn.prepareStatement("select * from user_info");
        resultSet = pps.executeQuery();
    }

    @Override
    public boolean hasNext() {
        //判断是否有下一条数据
        boolean next = false;
        try {
            next = resultSet.next();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return next;
    }

    //取数据
    @Override
    public String next() {
        String res = "";
        try {
            int id = resultSet.getInt(1);
            String name = resultSet.getString(2);
            int age = resultSet.getInt(3);
            String gender = resultSet.getString(4);
            res = id+","+name+","+age+","+gender;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return res;
    }
}
